<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <style type="text/css">
        body, html {
            width: 100%;
            height: 100%;
        }

        #l-map {
            height: 500px;
            width: 100%;
        }

        #r-result {
            width: 100%;
        }
    </style>
    <script type="text/javascript" src="/js/jquery.min.js"></script>
    <script type="text/javascript"
            src="http://api.map.baidu.com/api?v=2.0&ak=IYrcBQaaLVKXdIFjrMCAs7mOm3RcmrEI"></script>
    <title>推荐近地铁</title>
</head>
<body>
<jsp:include page="/WEB-INF/jsp/include/header2.jsp"/>
<form>
    <select name="cityName">
        <c:forEach var="cityName" items="${cityNames}">
            <option value="${cityName}"
                    <c:if test="${cityName eq param.cityName}">selected="selected"</c:if>>${cityName}</option>
        </c:forEach>
    </select>
    <select name="dateStr">
        <c:forEach var="dateStr" items="${dates}">
            <option value="${dateStr}" <c:if test="${dateStr eq param.dateStr}">selected="selected"</c:if>>
                    ${dateStr}
            </option>
        </c:forEach>
    </select>
    <input type="submit">
    <a href="/real/clear_cache" target="_blank">清除路线缓存</a>
</form>
<div id="l-map"></div>
<div id="r-result">
</div>
<div>
    <button id="statusBtn" onclick="nextAddress()">下一条</button>
    <br>
    调整路线:<input id="change-route">（无用：目前暂时没有跟地图绑定(时间效果详见<a href="/real/fix_address" target="_blank">地址修复</a> )）
    <div id="info">

    </div>
    <h4>当前线路分配情况</h4>
    <div id="current_route">
        <jsp:include page="include/current_route.jsp"/>
    </div>
    <h4>
        <ul>
            <li>右键红点分配路线</li>
            <li>推荐所有的单点，并计算路线</li>
            <li>推荐最近的点所在的线路，并计算线路</li>
            <li>蓝色的公共交通路线，红色的细直线是检测师当天任务</li>
        </ul>
    </h4>

</div>
</body>
</html>
<script type="text/javascript">

    var polylineColor = [
        "#E7E600",
        "#83e704",
        "#00e754",
        "#00e7db",
        "#0089e7",
        "#001be7",
        "#a100e7",
        "#e700e3",
        "#e7001f",
        "#eceee7"
    ];
    var polylineColorIndex = 0;

    var map = new BMap.Map("l-map");
    map.enableScrollWheelZoom(true);
    map.centerAndZoom("上海", 12);                   // 初始化地图,设置城市和地图级别。

    var ac = new BMap.Autocomplete({   //建立一个自动完成的对象
        "input": "change-route",
        "location": map
    });


    var transit = new BMap.TransitRoute(map, {
        renderOptions: {map: map},
        onSearchComplete: function (result) {
            console.info(arguments)
            if (transit.getStatus() == BMAP_STATUS_SUCCESS) {
                var plan = result.getPlan(0);
                var output = "到一下点所需的时间和距离";
                var end = result.getEnd();
                output += end.title + "  ";  // 自定义数据
                output += plan.getDuration(true) + "  ";  //获取时间
                output += plan.getDistance(true) + "<br>";  //获取距离


                polylineColorIndex++;
                if (polylineColorIndex >= polylineColor.length) {
                    polylineColorIndex = 0;
                }

                addPoint(end["point"], plan.getDuration(true), end.data, polylineColor[polylineColorIndex]);

                var firstPlan = result.getPlan(0);
                // 绘制步行线路
                for (var i = 0; i < firstPlan.getNumRoutes(); i++) {
                    var walk = firstPlan.getRoute(i);
                    if (walk.getDistance(false) > 0) {
                        // 步行线路有可能为0
                        map.addOverlay(new BMap.Polyline(walk.getPath(), {strokeColor: polylineColor[polylineColorIndex]}));
                    }
                }
                // 绘制公交线路
                for (i = 0; i < firstPlan.getNumLines(); i++) {
                    var line = firstPlan.getLine(i);
                    map.addOverlay(new BMap.Polyline(line.getPath(), {strokeColor: polylineColor[polylineColorIndex], strokeOpacity: 0.8}));
                }
                // 输出方案信息
                var s = [];
                for (i = 0; i < result.getNumPlans(); i++) {
                    s.push((i + 1) + ". " + result.getPlan(i).getDescription(false));
                }
//                document.getElementById("r-result").innerHTML = s.join("<br/>");
                document.getElementById("r-result").innerHTML += output;
            }
        }
    });

    //设置起终点图标
    transit.setMarkersSetCallback(function (result) {
        result[0].marker.hide();
        result[1].marker.hide();
    })


    var data = ${data};
    var index = 0;
    var curData = null;
    function nextAddress() {
//        polylineColorIndex = 0;

        document.getElementById("r-result").innerHTML = "";
        showCurrentRoute()
        map.clearOverlays();

        curData = data[index++];
        while (curData.done === 1) {
            curData = data[index++];
        }

        $("#info").html(index + ":" + curData.address + ":" + curData.checkTimeStr + ":" + curData.auctionId)

//        console.info(curData);

        var point = new BMap.Point(curData.lng, curData.lat);
        map.centerAndZoom(point, 13);

        var marker = new BMap.Marker(point);  // 创建标注
        map.addOverlay(marker);               // 将标注添加到地图中
        marker.setAnimation(BMAP_ANIMATION_BOUNCE); // 跳动的动画

        //创建右键菜单
        var markerMenu = new BMap.ContextMenu();
        markerMenu.addItem(new BMap.MenuItem('提交单线', submitOnlyPoint.bind(marker)));
//        markerMenu.addItem(new BMap.MenuItem('查询公交信息', findMetroInfo.bind(marker)));

        map.addOverlay(marker);
        marker.addContextMenu(markerMenu);
        marker.data = curData;


        $.post("/real/do_real_metro_and_line", {
            "lng": curData.lng, "lat": curData.lat
        }, function (lines) {
            showCurrentRoute()
            for (var lineIndex in lines) {
                if (lines[lineIndex].length <= 1) {
                    var p = new BMap.Point(lines[lineIndex][0].lng, lines[lineIndex][0].lat);
                    if (point.equals(p)) {
                        addPoint(p, "0分钟", lines[lineIndex][0]);
                    }

                    transit.search(point, {
                        title: lines[lineIndex][0].checkTimeStr + ":" + lines[lineIndex][0].auctionId,
                        point: p,
                        data: lines[lineIndex][0]
                    });

                } else {
                    var ps = [];
                    for (var pointIndex in lines[lineIndex]) {
                        ps[pointIndex] = new BMap.Point(lines[lineIndex][pointIndex].lng, lines[lineIndex][pointIndex].lat)

                        if (point.equals(ps[pointIndex])) {
                            addPoint(ps[pointIndex], "0分钟", lines[lineIndex][pointIndex]);
                        }

                        transit.search(point, {
                            title: lines[lineIndex][pointIndex].checkTimeStr + ":" + lines[lineIndex][pointIndex].auctionId,
                            point: ps[pointIndex],
                            data: lines[lineIndex][pointIndex]
                        });
                    }
                    var polyline = new BMap.Polyline(ps, {strokeColor: "red", strokeWeight: 2, strokeOpacity: 0.5});   //创建折线
                    map.addOverlay(polyline);
                }

            }
        })

    }
    var submitOnlyPoint = function (e, ee, marker) {
        $.post("/real/do_real_line", {
            "curAucId": marker.data.auctionId, "afterAucId": marker.data.auctionId
        }, function (date) {
            console.info(date)

        })
    }

    var insertAfterPoint = function (e, ee, marker) {
        $.post("/real/do_real_line", {
            "curAucId": curData.auctionId, "afterAucId": marker.data.auctionId
        }, function (date) {
            console.info(date)

        })
    }

    var showCurrentRoute = function () {
        $.get("/real/current_route", function (date) {
            $("#current_route").html(date)

        })
    }

    var addPoint = function (p, lable, inviData, color) {
        console.info(color)
        var myIcon = new BMap.Icon("http://api0.map.bdimg.com/images/trans_icons.png", new BMap.Size(22, 22), {
            imageOffset: new BMap.Size(0, -25)
        });
        var markerEnd = new BMap.Marker(p, {icon: myIcon});
        var label = new BMap.Label(lable + ":" + inviData["checkTimeStr"], {offset: new BMap.Size(20, -20)});
        if (!color) {
            color = "white";
        }
        label.setStyle({color: "black", backgroundColor: color, fontSize: "12px", opacity: 0.6})
        markerEnd.setLabel(label);


        map.addOverlay(markerEnd);
        markerEnd.enableDragging();
        markerEnd.data = inviData;

        var markerMenu = new BMap.ContextMenu();
        markerMenu.addItem(new BMap.MenuItem('插入到该点之后', insertAfterPoint.bind(markerEnd)));
        markerEnd.addContextMenu(markerMenu);
    }

</script>
